<template>

	<el-dialog v-model="dialogVisible" :title="dialogTitle" :before-close="closeDialog" class="elDiaLog" lock-scroll
		width="1000px" :close-on-click-modal="false" :close-on-press-escape="false">

		<div class="form-box" v-if="['act_edit','act_add'].includes(dialogStatus)" v-loading="loading2">
			<el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="150px">
				<el-form-item required label="所属工程" prop="engine_id">
					<div class=" " v-if="formData.engine_id">
						<el-text style="margin-right: 10px;" type="primary">{{selectRow.name}}</el-text>
						<el-button @click="bindGongCheng" circle>
							<template #icon><i-ep-position /></template>
						</el-button>
					</div>
					<el-button v-else type="primary" @click="bindGongCheng">绑定工程</el-button>
				</el-form-item>
				<el-form-item required label="业务名称" prop="name">
					<el-select v-model="formData.name" placeholder="请选择业务名称" class="defalut-width">
						<el-option v-for="item in BUSINESS_TYPE" :key="item.name" :label="item.name"
							:value="item.name" />
					</el-select>
				</el-form-item>
				<el-form-item required label="所属子公司/部门" prop="did">
					<el-tree-select 
						v-model="formData.did"
						:data="baseConfigStore.newExDepartmentList" check-strictly
						:render-after-expand="false" 
						style="width: 100%" 
						placeholder="请选择所属公司" >
							<template v-slot:default="{node, data }">
								<treeBlock :nodeItem="node" :dataItem="data" :typeClass="0"></treeBlock>
							</template>
						</el-tree-select>	
				</el-form-item>
				<el-form-item required label="申请内容" prop="content">
					<el-input v-model="formData.content" :rows="6" type="textarea" placeholder="请输入申请内容" maxlength="200"
						resize="none" show-word-limit />
				</el-form-item>
				<el-form-item label="附件内容" prop="files">
					<el-upload class="allwidth" name="file" v-model:file-list="formData.files" action="/api/upload"
						:data="{type:'file'}" show-file-list :auto-upload="true" :multiple="true"
						:on-success="(response:any, file:any, fileList:any) => {return imageBeforUploadSuccess(response, file, fileList,'files');}"
						:on-preview="onFilePreview" :before-upload="imageBeforUpload" :limit="10">
						<el-button type="primary">
							<template #icon><i-ep-upload-filled /></template>添加文件</el-button>
						<template #tip>
							<div class="el-upload__tip">
								<el-text size="small" type="info">{{feilType.pageShow}}</el-text>
							</div>
						</template>
					</el-upload>
				</el-form-item>
				<el-form-item label="审批人" prop="users">
					<div class="elTimeBox">
						<el-button v-if="approveList.type == 0" type="primary" style="margin-bottom: 20px;"
							@click="clickShenPiR('ac_addlist','users')"><template #icon><i-ep-CirclePlusFilled /></template>增加一级审批</el-button>
						<el-timeline>
							<el-timeline-item v-for="(item,index) in formData.users">
								<template #dot>
									<div class="el-timeline-item__node el-timeline-item__node--large">
										<el-icon><i-ep-user-filled /></el-icon>
									</div>
								</template>
								<div class="levelC">
									<div class="levelT">
										<h2 class="levelTH2" v-if="approveList.type == 0">第{{index + 1}}级审核人审批</h2>
										<h2 class="levelTH2" v-else>{{item.name}}</h2>
										<el-button v-if="index != 0" @click="delectUserClose(index,'users')" circle style="border: none;" >
											<template #icon><i-ep-Delete /></template>
										</el-button>
									</div>
									<div class="levelP">
										<div v-for="(ites,inds) in item.user_info" class="levelPi">
											<div class="levelPiU">
												<div class="levelPiUImgs">
													<img class="levelPiUImg" :src="ites.avatar" alt="">
												</div>
												<div class="levelPiUName">
													{{ites.name}}
												</div>
											</div>
											<div class="levelDelet" @click="closeUser(item,index,inds)">
												<i-ep-close style="width: 14px;" />
											</div>
										</div>
										<div class="levelP_add" >
											<el-button @click="addUser(item,index,'users')" >
												<template #icon><i-ep-CirclePlus /></template>添加
											</el-button>
										</div>
									</div>
								</div>
							</el-timeline-item>
						</el-timeline>
						<!-- <el-button type="primary" @click="clickShenPiR('ac_addlist')">添加审批人</el-button> -->
					</div>
				</el-form-item>
				<el-form-item>
					<div>
						<el-text tag="p" type="danger">1、本表适用于众联集团本部及子公司各类业务审批。</el-text>
						<el-text tag="p" type="danger">2、业务经办人员应充分准备业务资料，逐级报批。</el-text>
						<el-text tag="p" type="danger">3、申请内容详细、信息完整。</el-text>
					</div>
				</el-form-item>
			</el-form>
		</div>
		<div class="form-box" v-if="['act_info','act_audit'].includes(dialogStatus)" v-loading="loading2">

			<el-descriptions size="default" :column="1" border>
				<el-descriptions-item label-class-name="labelC1"
					label="所属工程：">{{dataInfo.engine?.name}}</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1" label="业务名称：">{{dataInfo.name}}
					<el-tag :type="titModel[dataInfo.status]?.type">{{titModel[dataInfo.status]?.title}}</el-tag>
				</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1" label="提单人：">{{dataInfo.user?.name}} <el-tag
						type="primary">{{dataInfo.add_time_text}}</el-tag></el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="所属子公司/部门：">{{dataInfo.department?.name}}</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1"
					label="申请内容：">{{dataInfo.content}}</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1" label="附件内容：">
					<div v-if="dataInfo.files?.length >0" v-for="(ite,ind) in dataInfo.files">
						<el-link @click="onFilePreview(ite)" type="primary">{{ind + 1}}.{{ite.name}}</el-link>
					</div>
					<el-link v-else type="info">无</el-link>
				</el-descriptions-item>
				<el-descriptions-item label-class-name="labelC1" label="审批人：">
					<template v-if="dataInfo.approve?.length <=0">
						无需审批
					</template>
					<div v-else class="elTimeBox">
						<el-timeline>
							<el-timeline-item v-for="(item,index) in dataInfo.approve?.user">
								<template #dot>
									<div class="el-timeline-item__node el-timeline-item__node--large">
										<el-icon>
											<i-ep-user-filled /></el-icon>
									</div>
								</template>
								<div class="levelC">
									<div class="levelT">
										<h2 class="levelTH2">第{{index + 1}}审批人</h2> 
									</div>
									<div class="levelP">
										<div v-for="(ites,inds) in item" class="levelPi">
											<div class="levelPiU">
												<div class="levelPiUImgs">
													<img class="levelPiUImg" :src="ites.avatar" alt="">
												</div>
												<div class="levelPiUName">
													{{ites.name}}
												</div>
											</div>
										</div>
									</div>
								</div>
							</el-timeline-item>
						</el-timeline>
					</div>
				</el-descriptions-item>

				<el-descriptions-item v-if="dataInfo.is_audit == 1" label-class-name="labelC1" label="法律意见书：">
					<div v-if="dataInfo.opinion?.length >0" v-for="(ite,ind) in dataInfo.opinion">
						<el-link @click="onFilePreview(ite)" type="primary">{{ind + 1}}.{{ite.name}}</el-link>
					</div>
					<el-link v-else type="info">未提交意见书</el-link>
				</el-descriptions-item>
			</el-descriptions>
			
			
			<template v-if="dataInfo.approve?.rule?.length>0">
				<el-divider content-position="left">审批日志</el-divider>
				<el-row>
					<div class="uTCont" v-for="uItem in dataInfo.approve?.rule" style="width: 100%;">
						<h4 class="uThead">{{uItem.name}}</h4>
						<el-table border  :data="uItem.user_info" style="width: 100%">
						<el-table-column label="审批人" width="200">
							<template #default="scope">
								<div class="uhead">
									<el-avatar :size="40" :src="scope.row.avatar" ></el-avatar>
									<span class="uheadN">{{scope.row.name}}</span>
								</div>
							</template>
						</el-table-column>
						<el-table-column label="审核状态" align="center" width="150">
							<template #default="scope">
								<el-tag v-if="scope.row.status == 0" type="info">待审核</el-tag>
								<el-tag v-if="scope.row.status == 1" type="success">已通过</el-tag>
								<el-tag v-if="scope.row.status == 2" type="danger">已驳回</el-tag>
							</template>
						</el-table-column>
						<el-table-column label="操作日期" width="220">
							<template #default="scope">
								<el-icon> <el-icon-timer></el-icon-timer></el-icon>
								<span style="margin-left: 10px">{{ scope.row.check_time }}</span>
							</template>
						</el-table-column>
						<el-table-column label="备注">
							<template #default="scope">
								{{ scope.row.mark }}
							</template>
						</el-table-column>
					</el-table> 
					</div>
				</el-row>
			</template>
			
			
			<template v-if="dataInfo.is_audit == 0 && ['act_audit'].includes(dialogStatus)">
				<el-divider content-position="left">提交法律意见书</el-divider>
				<el-form ref="dataFormRef2" :model="formDataF" :rules="rulesF" label-width="150px">
					<el-form-item required label="法律意见书" prop="opinion">
						<el-upload class="allwidth" name="file" v-model:file-list="formDataF.opinion"
							action="/api/upload" :data="{type:'file'}" show-file-list :auto-upload="true"
							:multiple="true"
							:on-success="(response:any, file:any, fileList:any) => {return imageBeforUploadSuccess2(response, file, fileList,'opinion');}"
							:on-preview="onFilePreview" :before-upload="imageBeforUpload" :limit="10">
							<el-button type="primary">
								<template #icon><i-ep-upload-filled /></template>添加文件</el-button>
							<template #tip>
								<div class="el-upload__tip">
									<el-text size="small" type="info">{{feilType.pageShow}}</el-text>
								</div>
							</template>
						</el-upload>
					</el-form-item>
				</el-form>
			</template>
		</div>
		<template #footer>
			<div class="dialog-footer">
				<el-button v-if="['act_info'].includes(dialogStatus)" :disabled="loading3" @click="closeDialog">关
					闭</el-button>
				<el-button v-if="['act_edit','act_add'].includes(dialogStatus)" type="primary" :loading="loading3"
					@click="handleSubmit">{{dialogStatus == 'act_edit'?'重新提交':'确 定'}}</el-button>
				<el-button v-if="['act_audit'].includes(dialogStatus)"
					:type="dataInfo.is_audit == 0?'warning':'primary'" :loading="loading3"
					@click="dataInfo.is_audit == 0?auditPage():''">{{dataInfo.is_audit == 0?"提交审查":"已审查"}}</el-button>
				<el-button v-if="['act_edit','act_add','act_audit'].includes(dialogStatus)" :disabled="loading3"
					@click="closeDialog">取 消</el-button>
			</div>
		</template>
		<!-- 绑定工程 -->
		<engineSelect v-if="binddialogSelect.visible" v-model="binddialogSelect.visible"
			:dialogTitle="binddialogSelect.title" @selectRowEngin="selectRowEngin"></engineSelect>


		
		<el-dialog v-model="dialogTree.visible" class="elDiaLog" lock-scroll title="选择审核人" width="1000px"
			@close="closeDialogTree">
			<div style="min-height: 300px;">
				<el-tree ref="treeRef" node-key="id" :data="options" :default-expanded-keys="[1]"
					:check-on-click-node="true" :show-checkbox="true"
					:props="{'children': 'children','label':'name','value':'id','disabled':'disable'}">
					<template #default="{ node, data }">
						<div class="lineDiv">
							<div v-if="data.avatar" class="lineimgs">
								<img class="lineimg" style="width: 20px;height: 20px;" :src="data.avatar" alt="">
							</div>
							<div class="lineTx">
								{{ node.label }}
							</div>
						</div>
					</template>
				</el-tree>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="getAllkeys">确定</el-button>
					<el-button @click="closeDialogTree">取消</el-button>
				</div>
			</template>
		
		</el-dialog>

	</el-dialog>


</template>
<script setup lang="ts">
	import { useRoute } from 'vue-router';
	import _ from 'lodash-es'
	import { feilType, onFilePreview } from "@/utils/funcall"
	import { useBaseConfigStore } from "@/store/modules/baseConfig";
	const baseConfigStore = useBaseConfigStore();
	import { BUSINESS_TYPE } from "@/utils/constant";

	import engineSelect from "./engineSelect.vue"

	// 获取接口地址
	import {
		addAudit,
		pullAuditStatus,
		updataAudit,
		getAudit
	} from "@/api/aggravate";
	//接口地址
	import {
		getDepartmentAndUser
	} from "@/api/doc";

	const props = defineProps({
		//数据列表索引值  例如 user ->对应着 vuex  == user_cxxxxx模块
		dialogTitle: {
			type: String,
			default: "添加信息"
		},
		dialogStatus: {
			type: String,
			default: "act_add"
		},
		dialogTableValue: {
			type: Object,
			default: () => { },
		},
		approveList:{
			type:Object,
			default: () => { },
		}
	});
	const titModel = ref([{
		title: '待审核',
		type: 'info',
		value: 0
	}, {
		title: '已通过',
		type: 'success',
		value: 1
	}, {
		title: '已驳回',
		type: 'danger',
		value: 2
	}])
	const emit = defineEmits(['update:modelValue', 'initRefreshList']);
	const dialogVisible = ref(false);
	const loading2 = ref(false);//新增或者修改加载load按钮
	const loading3 = ref(false);//新增或者修改加载load按钮
	// 数据的data-ref
	const dataFormRef = ref(ElForm);
	const dataFormRef2 = ref(ElForm);//法律意见书
	const formData = ref<any>({
		id:undefined,
		engine_id: "",//所属工程
		name: "",//业务名称
		did: "",//所属公司
		content: "",//申请内容
		files: [], //附件内容
		users: [[]] //审批人
	})
	const formDataF = ref<any>({
		id: undefined,
		is_audit: 1,
		opinion: []
	})
	
	const dataInfo = ref<any>({});
	const selectRow = ref<any>({});
	
	// const shenpiL = ref(['子公司执行董事/法人','集团分管副总','财务总监','集团监事','集团总经理'])
	
	watch(
		() => props.dialogTableValue,
		() => {
			if (props.dialogStatus == "act_audit") {
				let deepItem = _.cloneDeep(props.dialogTableValue)
				getAuditDetail(deepItem);
			}
			else if (props.dialogStatus == "act_info") {
				console.log('查看详情')
				// getDetailInfo(props.dialogTableValue)
				let deepItem = _.cloneDeep(props.dialogTableValue)
				getAuditDetail(deepItem);
			}
			else if (props.dialogStatus == "act_edit") {
				let deepItem = _.cloneDeep(props.dialogTableValue)
				getAuditDetail(deepItem);
			}
			else {
				console.log('添加信息')
				formData.value.users = JSON.parse(JSON.stringify(props.approveList.rule));
			}
		}, { deep: true, immediate: true })

	const rules = reactive<any>({
		engine_id: [{ required: true, message: '请先绑定工程', trigger: 'blur' }],
		name: [{ required: true, message: '请选择业务名称', trigger: 'blur' }],
		did: [{ required: true, message: '请选择所属公司/部门', trigger: 'blur' }],
		content: [{ required: true, message: '请输入申请内容', trigger: 'blur' }],
		users:[{required: true,  validator: userValidator, trigger: "blur"}]
	})
	/**
	 * 审批人校验器
	 */
	function userValidator(rule: any, value: any, callback: any) {
		if (!value || value.length === 0) {
			return callback(new Error("请选择审批人"));
		}
		const hasEmptyValue = value.some(item => item.length === 0);
		if (hasEmptyValue) {
			return callback(new Error("请选择审批人"));
		}
		return callback();
	}
	
	const rulesF = reactive<any>({
		opinion: [{ required: true, message: '请上传法律意见书', trigger: 'blur' }]
	})


	// users: [{ required: true, message: '请选择审批人', trigger: 'blur' }],
	// 提交新增内容/or修改
	function handleSubmit() {
		
		dataFormRef.value.validate((valid : boolean) => {
			console.log(valid)
			if (valid) {
				loading3.value = true;
				
				// let user = formData.value.users.map(group => group.map(item => item.uid));
				
				const rules = []
				for(var i = 0 ; i <formData.value.users.length;i++)
				{
					const item = formData.value.users[i]
					if(props.approveList.type==1)
					{
						rules.push({
							name:item.name,
							type:item.type,
							level:item.level,
							user:item.user_info.map(userObj => userObj.uid)
						})
					}
					else
					{
						rules.push({
							name:`第${i + 1}级审批人审批`,
							type:0,
							level:0,
							user:item.user_info.map(userObj => userObj.uid)
						})
					}
				}
				
				
				let data : any = {
					id:formData.value.id,
					engine_id: formData.value.engine_id,
					name:formData.value.name,
					did: formData.value.did,
					content: formData.value.content,
					files: formData.value.files,
					rule: rules
				}
	
				if (formData.value.id) {
					updataAudit(data).then((res) => {
						console.log(res)
						emit('initRefreshList');
						loading3.value = false;
						ElMessage({ message: '修改成功', type: 'success' })
						closeDialog();
					}).finally(() => {
						loading3.value = false;
					})
				}
				else {
					addAudit(data).then((res) => {
						console.log(res)
						emit('initRefreshList');
						loading3.value = false;
						ElMessage({ message: '添加成功', type: 'success' })
						closeDialog();
					}).finally(() => {
						loading3.value = false;
					})
				}
			}
		});
	}

	// 提交法律意见书
	function auditPage() {
		dataFormRef2.value.validate((valid : boolean) => {
			console.log(valid)
			if (valid) {
				ElMessageBox.confirm("确认要提交法律意见书?", "警告", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning",
				}).then(() => {
					pullAuditStatus(formDataF.value).then((res) => {
						console.log(res)
						emit('initRefreshList');
						loading3.value = false;
						ElMessage({ message: '提交成功', type: 'success' })
						closeDialog();
					}).finally(() => {
						loading3.value = false;
					})
				});
			}
		});




	}

	// 关闭弹窗
	function closeDialog() {
		if (!loading3.value) {
			emit('update:modelValue', false)
		}
	}

	/**
	 * 上传文件 之前的操作
	 */
	function imageBeforUpload(file : any) {
		var fileSize = file.size / 1024 / 1024 < feilType.size;
		const index = file.name.lastIndexOf(".");
		const ext = file.name.substr(index + 1).toUpperCase();
		if (feilType.extarr.indexOf(ext) == -1) {
			ElMessage({
				message: feilType.errorMes,
				type: 'error',
			})
			return false;
		}
		if (!fileSize) {
			ElMessage({
				message: feilType.prompt,
				type: 'error',
			})
			return false;
		}
	}
	// 图片和文件类型上传成功之后的回调
	function imageBeforUploadSuccess(response : any, file : any, fileList : any, el : any) {
		console.log(response, file, fileList, el)
		formData.value[el] = formData.value[el].map(item => {
			if (item.uid == file.uid) {
				const obj : any = {}
				obj.uid = file.uid
				obj.url = response.data.url
				obj.name = file.name
				return obj;
			}
			else {
				return item;
			}
		});
	}
	// 图片和文件类型上传成功之后的回调
	function imageBeforUploadSuccess2(response : any, file : any, fileList : any, el : any) {
		console.log(response, file, fileList, el)
		formDataF.value[el] = formDataF.value[el].map(item => {
			if (item.uid == file.uid) {
				const obj : any = {}
				obj.uid = file.uid
				obj.url = response.data.url
				obj.name = file.name
				return obj;
			}
			else {
				return item;
			}
		});
	}

	const binddialogSelect = reactive<any>({
		title: "选择工程", //弹窗标题
		visible: false,   //弹窗显示or隐藏
		status: "act_add", //弹窗状态类型  :添加 act_add 编辑 act_edit 详情 act_info  
		value: {}   		  //携带整条参数 row
	});
	// 绑定工程
	function bindGongCheng() {
		binddialogSelect.visible = true;
	}
	// 工程的回调函数
	function selectRowEngin(row) {
		console.log(row)
		selectRow.value = row;
		formData.value.engine_id = row.id;
	}
	// 获取详情
	function getAuditDetail(row) {
		loading2.value = true;
		getAudit({ id: row.id }).then((res) => {
			let data = res.data;
		
			formData.value.engine_id = data.engine_id;
			formData.value.name = data.name;
			formData.value.did = data.did;
			formData.value.content = data.content;
			formData.value.files = data.files;
			formData.value.users =  data.approve.rule;
			selectRow.value = data.department;

			dataInfo.value = res.data;
			formData.value.id = data.id;
			formDataF.value.id = data.id

		}).finally(() => {
			loading2.value = false;
		})
	}
	
	
	
	/**
	 * 添加审批人
	 */
	function clickShenPiR(type : string, el : any, index ?: any){
		
		if (type == "ac_delect") {
			formData.value[el].splice(index, 1)
		}
		else if (type == "ac_addlist") {
			formData.value[el].push({name: "",user_info:[]})
		}
	}
	
	// 审批流相关的代码 start
	const dialogTree = reactive<DialogOption>({
		visible: false,
	});
	const options = ref();
	const defaultUserKey = ref({
		userkey: [],
		index: -1,
		type: "",
	});
	const treeRef = ref();
	/**
	 * 打开弹窗添加审批流信息
	 */
	function addUser(e : any, index : number,type : string) {
		console.log(e)
		defaultUserKey.value.type = type;
		defaultUserKey.value.userkey = e.user_info.map((item : any) => '1_' + item.uid);
		defaultUserKey.value.index = index
		dialogTree.visible = true;
		nextTick(() => {
			treeRef.value!.setCheckedKeys(defaultUserKey.value.userkey, false)
		})
	}
	// 删除审批人-组
	function delectUserClose(index:any,type:any){
		const items = formData.value[type];
		if (items.length > 1) {
			items.splice(index, 1);
		}
	}
	/**
	 * 删除审批人
	 */
	function closeUser(e : any, index : number, inds : number) {
		formData.value.users[index]['user_info'].splice(inds, 1);
	
	}
	function getAllkeys() {
		formData.value.users[defaultUserKey.value.index]['user_info'] = treeRef.value!.getCheckedNodes(true);
		closeDialogTree();
	}
	/**
	 * 获取审批人列表
	 */
	function getShenPlist() {
		getDepartmentAndUser().then((res) => {
			options.value = res.data
		}).finally(() => {})
	}
	/**
	* 关闭 树形图 弹窗
	*/
	function closeDialogTree() {
		dialogTree.visible = false;
	}
	// 审批流相关的代码 End
	

	onMounted(() => {
		getShenPlist();
	});
</script>

<style lang="scss" scoped>

</style>